package com.bdqn.controller;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bdqn.pojo.ReturnPerson;
import com.bdqn.service.ReturnPersonService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
public class ReturnPersonController {
    @Resource
    private ReturnPersonService returnPersonService;

   @GetMapping("/list")
    public String list(Model model, String returnData, Integer pageNo){
       pageNo = pageNo == null ? 1 : pageNo;
       Page page = new Page(pageNo, 2);
       Page<ReturnPerson> pages = returnPersonService.getPage(returnData, page);
        model.addAttribute("returnData",returnData);
        model.addAttribute("pages",pages);
       return "index";
   }

   @GetMapping("/add")
   public String add(){
       return "save1";
   }

    @PostMapping("/save")
    public String doSave(HttpServletResponse response, ReturnPerson returnPerson) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        // 根据提交的表单数据中是否携带ID确定是增加还是修改
        Integer id = returnPerson.getId();
        int res = 0; // 执行结果
        if (id == null) { // 增加
            returnPerson.setCreateDate( new Date());
            res = returnPersonService.add(returnPerson);
        } else { // 修改
            res = returnPersonService.upd(returnPerson);
        }
        // 通过JavaScript跳转页面（重定向）
        return "redirect:/list";
    }

    @GetMapping("/upd/{id}")
    public String upd(Model model, @PathVariable  Integer id){
        ReturnPerson returnPerson = returnPersonService.selectId(id);
        model.addAttribute("returnPerson",returnPerson);
        return "save";
    }

    @PostMapping("/doAdd")
    public String doAdd(ReturnPerson returnPerson){
        returnPerson.setCreateDate( new Date());
        returnPersonService.add(returnPerson);
        return "redirect:/list";
    }

    @ResponseBody
    @PostMapping("/del")
    public String ajaxDel(Integer id) {
        // 返回结果
        Map<String, String> resMap = new HashMap<>();
        // 删除设备信息
        boolean del = returnPersonService.del(id);
        // 设置返回结果
        resMap.put("result", String.valueOf(del));

        // 转换为JSON格式字符串返回
        return JSON.toJSONString(resMap);
    }
}
